<template>
  <div class="app-container">

    <div style="padding: 20px 20px 0 20px;">
      授权角色：{{ this.$route.query.roleName }}
    </div>

    <el-tree
      ref="menuTree"
      style="margin: 20px 0"
      :data="menuList"
      node-key="id"
      show-checkbox
      default-expand-all
      :props="menuTreeProps"
    />

    <div style="padding: 20px 20px;">
      <el-button
        :loading="loading"
        type="primary"
        icon="el-icon-check"
        size="mini"
        @click="saveData"
      >保存</el-button>
      <el-button size="mini" icon="el-icon-refresh-right" @click="$router.push('/system/sysRole')">返回</el-button>
    </div>

  </div>
</template>
<script>
import api from '@/api/system/menu'
export default {
  data() {
    return {
      loading: false,
      menuList: [],
      menuTreeProps: {
        label: 'name',
        children: 'children'
      }
    }
  },
  created() {
    this.getMenuDataList()
  },
  methods: {
    getMenuDataList() {
      api.getMenusByRoleId(this.$route.query.id).then(res => {
        this.menuList = res.data
        // 显示勾选的菜单项
        const checkedMenus = this.showCheckedMenus(this.menuList)
        this.$refs.menuTree.setCheckedKeys(checkedMenus)
      })
    },
    /**
		 * @param {arr} menus 所有菜单列表
		 * @param {arr} checkedMenuArr 初始化一个需要返回给el-tree的选中菜单数组
		 */
    showCheckedMenus(menus, checkedMenuArr = []) {
      return menus.reduce((pre, item) => {
        if (item.select && item.children.length === 0) {
          pre.push(item.id)
        } else if (item.children) {
          this.showCheckedMenus(item.children, checkedMenuArr)
        }
        return pre
      }, checkedMenuArr)
    },
    // 保存数据
    saveData() {
      this.loading = true
      // 获取所有选中的节点信息;遍历节点数组,将其中的id值取出
      const menuIds = this.$refs.menuTree.getCheckedNodes(false, true).map(node => node.id)

      api.assignMenusToRole({
        'roleId': this.$route.query.id,
        'menuIdList': menuIds
      }).then(res => {
        this.$message({
          message: '可操作菜单分配成功',
          type: 'success',
          duration: 1500,
          onClose: () => {
            this.$router.push('/system/sysRole')
          }
        })
      })
    }
  }
}
</script>
